<?php
/**
 * Created by PhpStorm.
 * User: meng
 * Date: 2021/7/5
 * Time: 10:56 下午
 */

namespace app\middleware;
use app\admin\model\AdminMenuModel;
use app\admin\model\AdminRoleMenuModel;
use app\admin\model\AdminRoleUserModel;
use app\lib\exception\AuthException;
use app\utils\JwtUtils;
use \Closure;
use think\Request;


class CheckAuthorization
{
    /**
     * @param Request $request
     * @param Closure $next
     * @param string $name 路由名称
     * @return mixed
     * @throws AuthException
     */
    public function handle (Request $request, Closure $next, string $name) {
        $token = $request->header('Authorization');
        $jwt = new JwtUtils();
        $valid = $jwt->validatToken($token);
        $this->checkAuth($valid, $name);
        $request->userid = (int) $valid;
        return $next($request);
    }

    private function checkAuth ($userId, $name) {
//        halt($name);
        if (empty($name)) {
            return;
        }
        // 菜单中是否存在 不存在默认可以使用
        $menu = AdminMenuModel::where('api_route_name', $name)->find();
        if (empty($menu)) {
            return;
        }
        // 角色是否包含超级管理员 超级管理员默认有所有权限
        $roleIds = AdminRoleUserModel::where('user_id', $userId)->column('role_id');
        if (in_array(1, $roleIds)) {
            return;
        }
        // 所有权限菜单中是否包含该菜单
        $hasAccess = AdminRoleMenuModel::where('menu_id', $menu['id'])->where('role_id', 'in', $roleIds)->find();
        if (empty($hasAccess)) {
            throw new AuthException(10002);
        }
    }
}
